package com.xhwl.data.service.impl.personal;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xhwl.common.dto.cent.sdata.StaffAuditRecordDTO;
import com.xhwl.common.dto.detection.CompositeDetectionDTO;
import com.xhwl.common.enums.CredentialsEnum;
import com.xhwl.common.exception.DataException;
import com.xhwl.common.pojo.ResultJson;
import com.xhwl.common.pojo.cent.sdata.Account;
import com.xhwl.common.pojo.cent.sdata.Role;
import com.xhwl.common.pojo.cent.sdata.personnel.StaffAuditRecord;
import com.xhwl.common.query.cent.sdata.StaffAuditRecordQuery;
import com.xhwl.data.dao.personal.IStaffAuditRecordDao;
import com.xhwl.data.service.IAccountService;
import com.xhwl.data.service.IRoleService;
import com.xhwl.data.service.personal.IStaffAuditRecordService;
import com.xhwl.data.util.ValidatorUtil;
import com.xhwl.starter.detection.IDetectionService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author lanminjun
 * @Description:
 * @Date Create in 10:43 2023/02/15
 */
@Service
@Slf4j
public class StaffAuditRecordServiceImpl extends ServiceImpl<IStaffAuditRecordDao, StaffAuditRecord> implements IStaffAuditRecordService {

    @Autowired
    private IStaffAuditRecordDao staffAuditRecordDao;
    @Autowired
    private IRoleService roleService;
    @Autowired
    private IAccountService accountService;
    @Autowired
    private IDetectionService detectionService;
    //注册游客角色编码
    private String REGISTER_TOURIST_ROLE_CODE = "TOURIST1";

    @Override
    public ResultJson create(StaffAuditRecordDTO staffAuditRecordDTO, Account account) {
        staffAuditRecordDTO.setStatus((short) 1);
        ResultJson resultJson = dataCheck(staffAuditRecordDTO,account);
        if (!resultJson.getState()){
            return resultJson;
        }
        StaffAuditRecord staffAuditRecord = new StaffAuditRecord();
        BeanUtils.copyProperties(staffAuditRecordDTO,staffAuditRecord);
        staffAuditRecordDao.insert(staffAuditRecord);
        return ResultJson.success();
    }

    @Override
    public ResultJson edit(StaffAuditRecordDTO staffAuditRecordDTO, Account account) {
        ResultJson resultJson = dataCheck(staffAuditRecordDTO,account);
        if (!resultJson.getState()){
            return resultJson;
        }
        StaffAuditRecord staffAuditRecord = new StaffAuditRecord();
        BeanUtils.copyProperties(staffAuditRecordDTO,staffAuditRecord);
        staffAuditRecordDao.updateById(staffAuditRecord);
        return ResultJson.success();
    }

    @Override
    public Page<StaffAuditRecord> page(StaffAuditRecordQuery query, Page page) {
        return staffAuditRecordDao.page(query,page);
    }

    @Override
    public ResultJson checkStatu(Integer accountId,Integer enterpriseId) {
        List<Role> roles = roleService.getRoleListByAccountId(accountId);
        if (!roles.isEmpty()){
            QueryWrapper<StaffAuditRecord> queryWrapper = new QueryWrapper<>();
            queryWrapper.select("status");
            queryWrapper.eq("account_id",accountId);
            if (null != enterpriseId){
                queryWrapper.eq("enterprise_id",enterpriseId);
            }
            List<StaffAuditRecord> staffAuditRecords = list(queryWrapper);
            List<Short> status = staffAuditRecords.stream().map(StaffAuditRecord::getStatus).collect(Collectors.toList());
            if (StringUtils.isNotEmpty(roles.get(0).getCode()) && roles.get(0).getCode().equals(REGISTER_TOURIST_ROLE_CODE)){
                if (status.contains(Short.valueOf("1")) || status.contains(Short.valueOf("2"))){
                    return ResultJson.success("审核中");
                }else {
                    return ResultJson.success("是否申请认证？");
                }
            }
            if (status.contains(Short.valueOf("3"))){
                return ResultJson.success("审核通过");
            }
        }
        return ResultJson.success("允许申请员工认证");
    }

    private ResultJson dataCheck(StaffAuditRecordDTO staffAuditRecordDTO,Account account){
        if (null != staffAuditRecordDTO.getId()){
            StaffAuditRecord staffAuditRecord = getById(staffAuditRecordDTO.getId());
            if (null == staffAuditRecord){
                return ResultJson.fail("该认证信息不存在");
            }
            if (!account.getId().equals(staffAuditRecord.getAccountId())){
                return ResultJson.fail("账号不匹配");
            }
        }
        if (null == staffAuditRecordDTO.getStatus()){
            return ResultJson.fail("非法操作");
        }
        QueryWrapper<StaffAuditRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("status");
        queryWrapper.eq("account_id",staffAuditRecordDTO.getAccountId());
        queryWrapper.eq("is_deleted",false);
        List<StaffAuditRecord> staffAuditRecords = list(queryWrapper);
        if (!staffAuditRecords.isEmpty()){
            for (StaffAuditRecord staffAuditRecord : staffAuditRecords){
                if (staffAuditRecord.getStatus() == 1||staffAuditRecord.getStatus()==2){
                    if (staffAuditRecordDTO.getStatus() == 1 || staffAuditRecordDTO.getStatus() ==2){
                        return ResultJson.fail("已有审核中的认证，请耐心等待");
                    }
                }
                if (staffAuditRecord.getStatus() == 4){
                    if (staffAuditRecordDTO.getStatus() == 4){
                        return ResultJson.fail("已有审核失败的认证，请先删除");
                    }
                }
                if (staffAuditRecord.getStatus() == 3){
                    return ResultJson.fail("已认证成功，如需添加项目权限请联系企业管理员");
                }
            }
        }
        if (staffAuditRecordDTO.getStatus() == 4){
            return ResultJson.success();
        }
        if (StringUtils.isEmpty(staffAuditRecordDTO.getName())){
            return ResultJson.fail("名字不能为空");
        }else {
            if (20 < staffAuditRecordDTO.getName().length()) {
                return ResultJson.fail("请输入20个字符以内的姓名");
            }
        }
        // 名称、备注信息违规检查（腾讯检测能力）
        List<String> textList = new ArrayList<>();
        if (StringUtils.isNotEmpty(staffAuditRecordDTO.getRemark())) {
            textList.add(staffAuditRecordDTO.getRemark());
        }
        textList.add(staffAuditRecordDTO.getName());
        CompositeDetectionDTO compositeDetectionDTO = new CompositeDetectionDTO();
        compositeDetectionDTO.setTexts(textList);
        if (StringUtils.isNotEmpty(staffAuditRecordDTO.getFaceUrl())) {
            compositeDetectionDTO.setPics(Arrays.asList(staffAuditRecordDTO.getFaceUrl().split(",")));
        }
        Boolean detectionFlag = detectionService.detectionTextsAndImages(compositeDetectionDTO);
        if (!detectionFlag) {
            throw new DataException("名称或备注信息或图片违规，注册失败");
        }
        if (StringUtils.isEmpty(staffAuditRecordDTO.getPhone())){
            return ResultJson.fail("手机号必填");
        }else {
            if (!ValidatorUtil.isMobile(staffAuditRecordDTO.getPhone())) {
                return ResultJson.fail("请输入正确的手机号");
            }
        }
        if (null == staffAuditRecordDTO.getProjectId()){
            return ResultJson.fail("项目必须选择");
        }
        if (null == staffAuditRecordDTO.getEnterpriseId()){
            return ResultJson.fail("入驻企业必须选择");
        }
        if (CredentialsEnum.ID_CARD == staffAuditRecordDTO.getCardType() && !com.xhwl.common.utils.ValidatorUtil.isIDCard(staffAuditRecordDTO.getCardNo())) {
            return ResultJson.fail("身份证号格式错误");
        }
        if (StringUtils.isNotEmpty(staffAuditRecordDTO.getCardNo())){
            Account account1 = new Account();
            account1.setIdCard(staffAuditRecordDTO.getCardNo());
            accountService.accountUnique(account1);
        }
        if (null == staffAuditRecordDTO.getAccountId()){
            staffAuditRecordDTO.setAccountId(account.getId());
        }
        if (null == staffAuditRecordDTO.getSex()){
            staffAuditRecordDTO.setSex((short) 1);
        }
        return ResultJson.success();
    }
}

